import {TCP_IP,TCP_PROT,VIDEO_PROT,VIDEO_URL} from "@/utils/config.js"
import  {
	// 电梯项目调用这个即可
	jsonObjToByteArray,
	fmtData,
	encodeBase64String,
	stringToByteArray,
    crcCcitt,
    buildPacketFromJson,
    bufferToJson,
    getAJsonPacketFromSocket
} from "@/utils/bufferUtils.js"
import { javaCompatibleBase64Decode} from "@/utils/base64Utils.js"
// TCP 客户端字节处理
async function tcpClientBytes(host, port, base64str, buffSize) {
    try {
		console.log([host, port, base64str, buffSize])
        const decodedBytes = Uint8Array.from(atob(base64str), c => c.charCodeAt(0));
        const socket = await uni.connectSocket({
            url: `ws://${host}:${port}`
        });
        await uni.sendSocketMessage({
            data: decodedBytes.buffer
        });
        return new Promise((resolve, reject) => {
            uni.onSocketMessage((res) => {
                const buffer = new Uint8Array(res.data);
                const bytesRead = buffer.length;
                resolve(buffer.slice(0, bytesRead));
            });
            uni.onSocketError((res) => {
                reject(new Error("Socket error: " + res.errMsg));
            });
        });
    } catch (e) {
        console.log("Socket error: " + e.message);
        return stringToByteArray("Socket error: " + e.message);
    }
}

// TCP 客户端字节处理返回 JSON 列表
async function tcpClientByte(host, port, base64str, buffSize) {
    try {
        const response = await tcpClientBytes(host, port, base64str, buffSize);
        return getAJsonPacketFromSocket(response, buffSize);
    } catch (e) {
        console.log("Socket error: " + e.message);
        return [];
    }
}

// TCP 客户端
async function tcpClient(ip, port) {
    const jsonstr = "{\"request\":\"QueryStatus\"}";
    const checksum = crcCcitt(stringToByteArray(jsonstr), 0);
    const byteArray = buildPacketFromJson(jsonstr, checksum);
    const base64String = btoa(String.fromCharCode.apply(null, byteArray));
   // "{\"request\":\"QueryStatus\"} 添加crc后转成base64String= fucAAAAZ4wv5PXsicmVxdWVzdCI6IlF1ZXJ5U3RhdHVzIn0=
	const result = await tcpClientByte(ip, port, base64String, 1024);
    console.log(base64String);
    return result;
}


async function getData(ip ,port,jsonObj){
	return new Promise((resolve,reject)=>{
		const tcpclientbytes = uni.requireNativePlugin('tcpclientbytes');
		var base64String=fmtData(jsonObj)
        console.log('00000')
		// console.log(base64String)
		// 定义参数
		const params = {
		    ip ,
		    port,
			data:base64String,
			timeout:6000,
			buffSize:1024*1
		};
		console.log(params)
		
		tcpclientbytes.TcpClientBytes(params, res => {
		//插件回调
			// console.log(res)
		var str=encodeBase64String(res)

		console.log(str)
		try{
			resolve(str[0][0]||str[0]||str)
		}catch(e){
			console.log(e)
		}
			// console.log(str)
		})
	})

}
export function tcpRequest(jsonObj,ipaddr=""){
    let dot1=uni.getStorageSync('dot1')
    let dot2=uni.getStorageSync('dot2')
    let dot3=uni.getStorageSync('dot3')
    let dot4=uni.getStorageSync('dot4')
    let port2=uni.getStorageSync('port2')
	var ip=''
    if(dot1&&dot2&&dot3&&dot4){
        ip=`${dot1}.${dot2}.${dot3}.${dot4}`
    }else{
        ip=TCP_IP
    }
	var port =''
    if(port2){
        port=port2
    }else{
        port=TCP_PROT
    }
	if(ipaddr != ""){
		var arr=ipaddr.split(":");
		ip= arr[0]
		if(arr[1]){
			port =arr[1]
		}
	}
	if(!port){
		port=80
	}
	return getData(ip,port,jsonObj)
}
// 导出函数供外部使用
export default {
	// 电梯项目调用这个即可
	tcpRequest,
	getData,
	jsonObjToByteArray,
	fmtData,
	encodeBase64String,
	 javaCompatibleBase64Decode,
	// base64ToBytes,
	stringToByteArray,
    crcCcitt,
    buildPacketFromJson,
    bufferToJson,
    getAJsonPacketFromSocket,
    tcpClientBytes,
    tcpClientByte,
    tcpClient
};